package com.teng.mrliuproject.ui.vmodel

import androidx.databinding.ObservableField
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSONObject
import com.teng.mrliuproject.base.RouteManages
import com.teng.mrliuproject.entity.LoginBean
import com.teng.mrliuproject.net.Api
import com.teng.mrliuproject.net.ApiCode
import com.teng.mylibrary.base.BaseViewModel
import com.teng.mylibrary.callback.livedata.event.EventLiveData
import com.teng.mylibrary.net.RetrofitHelper
import com.teng.mylibrary.util.SPUtil

/**
 * Description:
 * Author:       liuteng
 * CreateDate:   2022/4/15 13:41
 * UpdateRemark: 更新说明
 */
class LoginVModel : BaseViewModel() {

    val isRemember = ObservableField(false)
    val account = ObservableField("")
    val password = ObservableField("")
    val canLogin = ObservableField(false)
    val myUc by lazy { UIChangeObservable() }

    inner class UIChangeObservable {
        val checkLogin: EventLiveData<Void> = EventLiveData()
    }

    override fun initData() {
        super.initData()

        isRemember.set(SPUtil.isRemember())
        account.set(SPUtil.getAccount())
        if (SPUtil.isRemember()) {
            password.set(SPUtil.getPassword())
        }
    }

    fun refreshOrg() {
        getOrgList()
    }

    fun getOrgList() {
        requestData(
            ApiCode.GETORGLIST,
            RetrofitHelper.create(Api::class.java)
                .getOrgList(RetrofitHelper.getRequestBody(null))
        )
    }

    fun loginApp() {
        ARouter.getInstance().build(RouteManages.MAIN_ACTIVITY).navigation()
        uc.finishPageEvent.call()
      /*  if (canLogin.get() == true) {
            requestData(
                ApiCode.LOGIN,
                RetrofitHelper.create(Api::class.java)
                    .login(account.get().toString(), password.get().toString())
            )
        } else {
            myUc.checkLogin.call()
        }*/
    }

    fun goSetting() {
        ARouter.getInstance().build(RouteManages.SYSTEM_CONFIG_ACTIVITY).navigation()
    }

    override fun <T> returnData(code: Int, dataEntity: T?) {
        super.returnData(code, dataEntity)
        when (code) {
            ApiCode.GETORGLIST -> {

            }
            ApiCode.LOGIN -> {
                val bean = dataEntity as LoginBean?
                bean?.let {
                    SPUtil.setAccount(account.get().toString())
                    SPUtil.setPassword(password.get().toString())
                    SPUtil.setUsername(it.F_RealName)
                    SPUtil.setUserId(it.F_UserId)
                    SPUtil.setRemember(isRemember.get() == true)
                    ARouter.getInstance().build(RouteManages.MAIN_ACTIVITY).navigation()
                    uc.finishPageEvent.call()
                }
            }
        }
    }
}